package com.gitee.wsl.compose.ui.textfield.color

import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.input.TextFieldValue
import com.gitee.wsl.compose.ui.base.TextField


@OptIn(ExperimentalStdlibApi::class)
@Composable
fun TextField.HexColor(
    color: Color,
    onValueChanged: (color: Color) -> Unit,
    alphaEnabled: Boolean,
    modifier: Modifier = Modifier
) {
    //TODO TextField clean button
    val hexFormat = remember {
        HexFormat {
            upperCase = true
            number.removeLeadingZeros = false
        }
    }
    val textFieldValue = remember {
        mutableStateOf(TextFieldValue("#"))
    }

    val isTextFieldInput = remember { mutableStateOf(false) }
    LaunchedEffect(color) {
        if (color.toArgb() != textFieldValue.value.text.removePrefix("#").toIntOrNull(16)) {
            val hexString = color.value.toHexString(hexFormat)
            textFieldValue.value = textFieldValue.value.copy(
                text = "#" + hexString.substring(
                    minOf(
                        if (!alphaEnabled) 2 else 0,
                        color.value.toHexString(hexFormat).lastIndex
                    ),
                    minOf(8, color.value.toHexString(hexFormat).length)
                )
            )
        }
    }
    TextField(
        value = textFieldValue.value,
        onValueChange = {
            isTextFieldInput.value = true
            val updateColor = textFieldValue.value.text != it.text
            textFieldValue.value = it
            if (updateColor) {
                val newValueText = it.text.removePrefix("#")
                val count = 8 - newValueText.length
                val formatNewValueText = if (count > 0) {
                    "FF00000000".substring(0, count) + newValueText
                } else {
                    newValueText
                }
                val newValue = formatNewValueText.toLongOrNull(16)
                if (newValue != null && newValue in 0L..0xFFFFFFFFL) {
                    onValueChanged(Color(newValue))
                }
            }
            isTextFieldInput.value = false
        },
        modifier = modifier
    )
}